<template>
<div id="main">
  <div class="nav-contain long">
        <my-nav class="mynav" left="首页" mid="返回我的问卷" right="登出" @toHome='toHome' @toAbout='toPersonQuestion' @topChange='topChange'></my-nav>
  </div>
  <div style="width:100%;height:100%;margin-top:5rem;">
  <div v-loading="is_loading">
    <el-card class="editor-main editor-head" shadow="never">
      <div class="header-form">
        <el-button
          v-if="is_preview"
          type="primary"
          icon="el-icon-edit"
          @click="is_preview = false">
          返回编辑
        </el-button>
        <el-button
          v-else
          type="primary"
          icon="el-icon-camera"
          @click="$refs.fill.changeAnswer(0, null); is_preview = true">
          预览问卷
        </el-button>
        <el-button type="primary" icon="el-icon-message" @click="save">保存问卷</el-button>
        <el-button type="primary" icon="el-icon-upload2" @click="publish">发布问卷</el-button>
      </div>
    </el-card>

    <Fill v-show="is_preview" :preview_data="form" ref="fill">
    </Fill>
    <el-card class="editor-main" v-show="!is_preview">
      <div class="title-box">
        <el-input
          class="qtitle title-sep"
          v-model="form.title"
          size="large"
          placeholder="请输入标题">
        </el-input>
        <el-input
          class="qdescription title-sep"
          type="textarea"
          size="mini"
          autosize
          placeholder="问卷说明"
          v-model="form.description">
        </el-input>
      </div>

      <div class="due-picker">
        <el-form :inline="true">
          <el-form-item label="截止时间">
            <el-switch v-model="form.has_due"></el-switch>
          </el-form-item>
          <el-form-item v-if="form.has_due">
            <el-date-picker
              v-model="form.due"
              type="datetime"
              placeholder="Select date and time">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>

      <div class="qlist">

        <Question
          v-for="(question, index) in form.questions"
          :key="index"
          class="qbox"
          v-model="form.questions[index]"
          :index="index"
          :type="form.type"
          :questions="form.questions"
          @up="move_up(index)"
          @down="move_down(index)"
          @duplicate="duplicate(index)"
          @delete="deleteq(index)">
        </Question>

        <el-card class="box-card qbox new-q-card">
          <el-dropdown @command="new_question" class="add-button">
            <el-button class="" icon="el-icon-plus">添加问题</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="radio">单选题</el-dropdown-item>
              <el-dropdown-item command="checkbox">多选题</el-dropdown-item>
              <el-dropdown-item command="input">填空题</el-dropdown-item>
              <el-dropdown-item command="rating" v-if="form.type != 'exam'">
                评分题
              </el-dropdown-item>
              <el-dropdown-item command="location" v-if="form.type != 'exam'">
                定位
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-card>

      </div>
    </el-card>
  </div>
</div>
</div>
</template>

<script>
import { v4 as uuid } from 'uuid'
import MyNav from '../components/MyNav.vue';
import Question from '@/components/editor/Question.vue'
import Questionnaire from '@/api/Questionnaire.js'

import Fill from './Fill.vue'

const QUESTION_FACTORY = {
  radio() {
    return {
      "choices": [""],
      "radio_answer": null,
      "capacity": [0],
      "has_capacity": false
    }
  },
  input() {
    return {
      "text": "",
      "input_answer": ""
    }
  },
  rating() {
    return {
      "number": 5
    }
  },
  checkbox() {
    return {
      "choices": [""],
      "checkbox_answer": [],
      "capacity": [0],
      "has_capacity": false
    }
  },
  location() {
    return {}
  }
}

const build_question = (type) => {
  const q = QUESTION_FACTORY[type]()
  q.title = ""
  q.description = ""
  q.nullable = false
  q.type = type
  q.score = 1
  q.uuid = uuid()
  q.wants = []
  q.hide = false
  q.interlock_combinator = "or"
  return q
}

const INITIAL_QUESTIONS = {
  normal() {
    return []
  },
  vote() {
    const q = build_question("radio")
    q.title = "投票"
    return [
      q
    ]
  },
  limit() {
    const name = build_question("input")
    name.title = "姓名"

    const tel = build_question("input")
    tel.title = "手机号"

    const q = build_question("radio")
    q.has_capacity = true
    q.title = "报名"
    return [
      name,
      tel,
      q
      ]
  },
  exam() {
    const name = build_question("input")
    name.title = "姓名"
    name.score = 0

    const no = build_question("input")
    no.title = "学号"
    no.score = 0

    return [
      name, no
      ]
  },
  pos() {
    const name = build_question("input")
    name.title = "姓名"

    const no = build_question("input")
    no.title = "学号"

    const body_temp = build_question("radio")
    body_temp.title = "体温"
    body_temp.choices = [...Array(5).keys()].map((x) => (x/2 + 35).toString())

    const track = build_question("radio")
    track.title = "有无去过高风险地区"
    track.choices = ["有", "无"]

    const symptom = build_question("radio")
    symptom.title = "有无新冠症状"
    symptom.choices = ["有", "无"]

    const pos = build_question("location")
    pos.title = "定位"

    return [
      name,
      no,
      body_temp,
      track,
      symptom,
      pos
      ]
  }
}

export default {
  components: {
    Question,
    Fill,
    MyNav,
  },
  data () {
    const is_change = Boolean(this.$route.params.id)
    var qtype = this.$route.query.type || "normal"

    var questions = []
    if (!is_change) {
      questions = INITIAL_QUESTIONS[qtype]()
    }

    if (qtype === "pos") {
      qtype = "normal"
    }

    return {
      is_loading: false,
      is_change: is_change,
      is_preview: this.$route.query.preview === "true",
      form: {
        title: '',
        description: '',
        has_due: false,
        due: (new Date(Date.now() + 24*3600*1e3)).toISOString(),
        type: qtype,
        questions: questions
      },
    }
  },
  mounted() {
    if (this.is_change) {
      this.update()
    }
  },
  methods: {
                toHome:function(){
                this.$router.push('/home');
            },
            toPersonQuestion:function(){
                this.$router.push('/manage');
            },
    topChange:function(){
      console.log('topchange');
      const top=document.querySelector('.nav-contain');
      if(top.className.indexOf('short')!==-1){
        top.classList.remove('short');
        top.classList.add('long');
      }else{
        top.classList.remove('long');
        top.classList.add('short');
      }
    },
    update() {
      this.is_loading = true
      Questionnaire.get(this.$route.params.id)
        .then((response) => {
          Object.assign(this.form, response.data)
        })
        .catch((error) => {
          console.log(error)
          this.$notify({
            title: 'Could not reach the API.',
            message: error.response.data.detail || error
          })
        })
        .finally(() => this.is_loading = false)
    },
    submit() {
      this.is_loading = true;
      return (this.is_change ? 
        Questionnaire.update(this.$route.params.id, this.form) :
        Questionnaire.add(this.form)
      )
        .then((response) => {
          this.is_loading = false
          this.$message("成功")
          return response
        })
        .catch((error) => {
          this.is_loading = false
          console.log(error)
          this.$notify({
            title: 'Could not reach the API.',
            message: error.response.data.detail || error.toString()
          })
          throw error
        })
    },
    save() {
      this.submit()
        .then(() => this.$router.go(-1))
    },
    publish() {
      this.submit()
        .then((response) => {
          this.is_loading = true;
          var id = this.$route.params.id || response.data.data
          Questionnaire.publish(id)
            .then(() => {
              this.$message("发布成功")
              this.$router.push("/share/"+id)
            })
            .catch((error) => {
              console.log(error)
              this.$notify({
                title: 'Could not reach the API.',
                message: error
              })
            })
            .finally(() => this.is_loading = false)
        })
    },

    move_up(index) {
      if (index == 0) {
        return
      }
      var tmp = this.form.questions.splice(index, 1)[0]
      this.form.questions.splice(index - 1, 0, tmp)
    },
    move_down(index) {
      if (index + 1 == this.form.questions.length) {
        return
      }
      var tmp = this.form.questions.splice(index, 1)[0]
      this.form.questions.splice(index + 1, 0, tmp)
    },
    duplicate(index) {
      var tmp = JSON.parse(JSON.stringify(this.form.questions[index]))
      this.form.questions.splice(index + 1, 0, tmp)
    },
    deleteq(index) {
      const uuid = this.form.questions[index].uuid
      this.form.questions.splice(index, 1)
      this.form.questions
        .forEach(x => x.wants.filter(y => y.uuid === uuid)
          .forEach(y => x.wants.splice(x.wants.indexOf(y), 1)))
    },
    new_question(type) {
      const q = build_question(type)
      q.nullable = this.form.type != 'exam'
      this.form.questions.push(q)
    },
  },
  computed: {
  }
}
</script>

<style scoped lang="sass">
.editor-main
  max-width: 20cm
  margin: auto

.editor-head
 border: 0

.new-q-card
  text-align: center

.qtitle
  max-width: 10cm

.title-sep
  margin: .1cm

.title-box
  text-align: center
  margin: .5cm

.header-form
  text-align: right
</style>

<style scoped>
.qlist {
  padding: 20px;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
}
.qbox {
  width: 100%;
  margin-top: 20px;
  border-radius: 0;
}
.qbox:first-child {
  margin-top: 0;
}
.qbox-new {
  padding: 20px;
  border: 1px solid #dcdfe6;
  text-align: center;
}
#main{
   display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.nav-contain{
  height:15vh;width:100vw;display:flex;justify-content:space-around;align-items:center;
  background-image:url('../assets/survey2.jpg') ;
  background-size: cover;
  opacity: 0.8;
}
.short{
  height:5vh;
  transition: all 0.7s ease-in-out;
}
.long{
  height:15vh;
  transition: all 0.7s ease-in-out;
}
.mynav{
  height:0.2rem;
  width:5rem;
}
</style>

